package com.blog.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * @author 任浩
 * @version 1.0
 */

@Component
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送数据的方法
     * @param to  //要发送的地方
     * @param subject //发送标题
     * @param context //发送内容
     */
    public void sendMsg(String to , String subject, String context){
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //创建一个类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

            //设置发送者
            helper.setFrom(from);
            //设置发送到哪
            helper.setTo(to);
            //设置发送内容的标题
            helper.setSubject(subject);
            //设置发送的内容
            helper.setText(context,true);

            //然后发送数据
            mailSender.send(helper.getMimeMessage());
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
